package gestionBulletins.view;

import gestionBulletins.controller.MyTableModel;
import gestionBulletins.controller.TableAdherentsActionListener;
import gestionBulletins.controller.TableAdherentsMouseAdapter;
import gestionBulletins.model.Adherent;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

public class ConsultWindow extends JFrame {

	public JTable table;
	public MyTableModel tableModel;
	public JMenuItem infosAdherent;
	public JMenuItem effacerAdherent;
	public JMenuItem infosEnfants;
	public JComboBox criteres;
	public JTextField textRecherche;
	public JButton boutonRecherche;
	public JButton boutonExport;
	public InfosAdherentWindow infosAdherentWindow;
	private int selectedRow;
	private static final long serialVersionUID = 1L;

	public ConsultWindow(MyTableModel tableModel) {
		super();
		this.setDefaultCloseOperation(HIDE_ON_CLOSE);
		this.setPreferredSize(new Dimension(800, 300));
		this.tableModel = tableModel;
		selectedRow = 0;
		infosAdherentWindow = new InfosAdherentWindow(tableModel.getDaoFactory());
		infosAdherentWindow.addObserver(tableModel);
		setTitle("Consultation de la base de données");
		initComposantsGraphiques();
		setupFrame();
		pack();
		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
		this.setLocation((dim.width - getSize().width) / 2,
				(dim.height - getSize().height) / 2);

	}

	public InfosAdherentWindow getInfosAdherentWindow() {
		return infosAdherentWindow;
	}

	/* pour test séparé */
	public static void main(String[] args) {
		ConsultWindow window = new ConsultWindow(null);
		//window.pack();
		window.setVisible(true);

	}

	private void initComposantsGraphiques() {
		table = new JTable(tableModel);
		String[] strCriteres = { "Tout", "Nom", "Prénom", "Commune", "Ile"};
		criteres = new JComboBox(strCriteres);
		textRecherche = new JTextField();
		boutonRecherche = new JButton("Filtrer");
		infosAdherent = new JMenuItem("infos de l'adhérent");
		infosEnfants = new JMenuItem("Voir les enfants");
		effacerAdherent = new JMenuItem("Effacer cet adhérent");
		infosAdherent.addActionListener(new TableAdherentsActionListener(this));
		infosEnfants.addActionListener(new TableAdherentsActionListener(this));
		effacerAdherent.addActionListener(new TableAdherentsActionListener(this));
		boutonExport = new JButton("Exporter vers Excel");
	}

	public void repaint() {
		//System.out.println("on me repaint !");
		table.revalidate();
		table.repaint();
		super.repaint();
	}

	private void setupFrame() {

		Container pane = getContentPane();
		pane.setLayout(new BorderLayout());
		JScrollPane sp = new JScrollPane(table);
		pane.add(sp, BorderLayout.CENTER);

		JPanel jp = new JPanel();
		BoxLayout bl = new BoxLayout(jp, BoxLayout.LINE_AXIS);
		jp.setLayout(bl);
		jp.add(new JLabel("Recherche"));
		jp.add(Box.createRigidArea(new Dimension(20,0)));
		jp.add(textRecherche);
		jp.add(Box.createRigidArea(new Dimension(20,0)));
		jp.add(boutonRecherche);

		JPanel basDeTable = new JPanel();
		BoxLayout bll = new BoxLayout(basDeTable, BoxLayout.PAGE_AXIS);
		basDeTable.setLayout(bll);
		basDeTable.add(Box.createRigidArea(new Dimension(0,5)));
		basDeTable.add(jp);
		basDeTable.add(Box.createRigidArea(new Dimension(0,5)));
		basDeTable.add(boutonExport);
		pane.add(basDeTable, BorderLayout.SOUTH);

		/* menu contextuel */
		JPopupMenu menu = new JPopupMenu();
		menu.add(infosAdherent);
		menu.add(infosEnfants);
		menu.add(effacerAdherent);
		table.addMouseListener(new TableAdherentsMouseAdapter(this, menu));
		final TableRowSorter<TableModel> rs = new TableRowSorter<TableModel>(tableModel);
		table.setRowSorter(rs);

		/* comportement bouton filtre */
		boutonRecherche.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String regex = textRecherche.getText();
				if (regex.isEmpty()) {
					rs.setRowFilter(null);
				}
				else {
					rs.setRowFilter(RowFilter.regexFilter(regex));
				}
			}
		});
		
		textRecherche.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String regex = textRecherche.getText();
				if (regex.isEmpty()) {
					rs.setRowFilter(null);
				}
				else {
					rs.setRowFilter(RowFilter.regexFilter(regex));
				}
			}
		});

		/* comportement bouton export */
		boutonExport.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				JFileChooser jc = new JFileChooser();
				FileNameExtensionFilter filtre = new FileNameExtensionFilter("fichiers CSV", "csv");
				jc.setFileFilter(filtre);
				int retval = jc.showSaveDialog(ConsultWindow.this);
				//System.out.println("valeur de retour du JFileChooser:" + retval);
				//System.out.println(jc.getSelectedFile().getPath());
				String path = jc.getSelectedFile().getAbsolutePath();
				if (path == null) {
					path = "adherents";
				}
				if (!path.contains(".csv")) {
					path = path + ".csv";
				}
				File f = new File(path);
				PrintWriter pw = null;
				StringBuilder sb = new StringBuilder();
				try {
					pw = new PrintWriter(f);
				}
				catch (IOException ioe) {
					ioe.printStackTrace();
				}
				
				/* dégueu: je croise la selection de la JTable avec tout les adhérents */
				ArrayList<Adherent> allAdherents = ConsultWindow.this.tableModel.getSelection();
				ArrayList<Adherent> selection = new ArrayList<Adherent>();
				JTable t = ConsultWindow.this.table;
				for (int i = 0; i < t.getRowCount(); i++) {
					String rowNom = (String)t.getValueAt(i, 1);
					String rowPrenom1 = (String)t.getValueAt(i, 2);
					String rowBirth = (String)t.getValueAt(i, 3);
					for (Adherent candidat : allAdherents) {
						if (candidat.getNom().compareTo(rowNom) == 0 &&
								candidat.getPrenom1().compareTo(rowPrenom1) == 0){
							String candidatBirth = candidat.getDateNaissanceJour() + "-" +
												   candidat.getDateNaissanceMois() + "-" +
												   candidat.getDateNaissanceAnnee();
							if (candidatBirth.compareTo(rowBirth) == 0) {
								selection.add(candidat);
								break;
							}
						}
					}
				}
				
				pw.println("etat civil;nom;prenom1;prenom2;prenom3;nom d'epouse;date de naissance;ile;commune;adresse;tel bureau;tel domicile;vini;profession;religion;situation familiale;nom conjoint;prenom conjoint;nb enfants;possède une carte d'electeur;a voté;numero de bureau de vote;numero d'electeur;");
				for (Adherent adherent : selection) {
					sb.append(adherent.getEtatCivil() + ";");
					sb.append(adherent.getNom() + ";");
					sb.append(adherent.getPrenom1() + ";");
					sb.append(adherent.getPrenom2() + ";");
					sb.append(adherent.getPrenom3() + ";");
					sb.append(adherent.getNomDEpouse() + ";");
					sb.append(adherent.getDateNaissanceJour() + "-" + adherent.getDateNaissanceMois() + "-" + adherent.getDateNaissanceAnnee() + ";");
					sb.append(adherent.getIle() + ";");
					sb.append(adherent.getCommune() + ";");
					sb.append(adherent.getAdresse() + ";");
					sb.append(adherent.getTelBureau() + ";");
					sb.append(adherent.getTelDomicile() + ";");
					sb.append(adherent.getVini() + ";");
					sb.append(adherent.getProfession() + ";");
					sb.append(adherent.getReligion() + ";");
					sb.append(adherent.getSituationFamiliale() + ";");
					sb.append(adherent.getNomConjoint() + ";");
					sb.append(adherent.getPrenomConjoint() + ";");
					sb.append(adherent.getNbEnfants() + ";");
					sb.append(adherent.getHasCard() + ";");
					sb.append(adherent.getHasVoted() + ";");
					sb.append(adherent.getNumBureau() + ";");
					sb.append(adherent.getNumElecteur() + ";");
					pw.println(sb);
					sb.setLength(0);
				}
				pw.close();
				JOptionPane.showMessageDialog(ConsultWindow.this, "Le fichier a bien été enregistré, vous pouvez l'ouvrir avec Excel");
			}
		});
	}

	public int getSelectedRow() {
		return selectedRow;
	}

	public void setSelectedRow(int selectedRow) {
		this.selectedRow = selectedRow;
	}
}
